<style lang="less">
    .user {
        .ivu-table th {
            background-color: #005178;
            color: #fff;
        }
    }
</style>
<template>
    <div class="roleList">

        <Modal   :draggable="true" v-model="bindMenuModal.bindMenuWin"
               title="权限设置"
               @on-ok="bindMenu"
               ok-text="提交"
               :loading="bindMenuModal.loading"
               @on-visible-change="resetMenu"
               :mask-closable="false"
               >
            <Tabs value="name1">
                <TabPane label="菜单权限" name="name1">
                    <Tree ref="menuTree" :data="bindMenuModal.tree" show-checkbox></Tree>
                </TabPane>
                <TabPane label="首页模块" name="name2">
                    <Tree ref="menuModuleTreeHome" :data="bindMenuModal.moduleTreeHome" show-checkbox></Tree>
                </TabPane>
                <TabPane label="销售模块" name="name3">
                    <Tree ref="menuModuleTreeStatistics" :data="bindMenuModal.moduleTreeStatistics" show-checkbox></Tree>
                </TabPane>
            </Tabs>
        </Modal>
        <Modal   :draggable="true" v-model="saveRoleModal.saveRoleWin"
               :title="saveRoleModal.modalName"
               @on-ok="saveRoleInfo('ruleValidation')"
               ok-text="提交"
               :loading="saveRoleModal.loading"
               :mask-closable="false">
            <Form ref="ruleValidation" :model="saveRoleModal.saveRole" :label-width="50"
                  :rules="saveRoleModal.ruleValidation">
                <FormItem label="名称:" prop="name">
                    <Input v-model="saveRoleModal.saveRole.name" placeholder="请输入名称"/>
                </FormItem>
                <FormItem label="描述:" prop="detail">
                    <Input v-model="saveRoleModal.saveRole.detail" type="textarea" :rows="4" placeholder="请输入描述"/>
                </FormItem>
            </Form>
        </Modal>
        <Row class="mb-10">
            <Col span="16">
                <Button type="primary" icon="md-add" class="ivu-btn-default" @click="showSaveRoleModal(null)">新增
                </Button>
                <Button type="primary" icon="md-close" class="ivu-btn-default" @click="delRole(selectionIds)">删除
                </Button>
                <Button type="primary" icon="md-refresh" class="ivu-btn-default" @click="refresh">刷新</Button>
            </Col>
            <Col span="8">
                <Button type="primary" icon="ios-redo" class="ivu-btn-default" @click="resetSearchData"
                        style="float: right;margin-left: 2px">重置
                </Button>
                <Button type="primary" icon="md-search" class="ivu-btn-default" @click="search"
                        style="float: right;margin-left: 2px">查询
                </Button>
                <Input v-model="searchData.name" placeholder="请输入职位名称" style="width: 50%;float: right"/>
            </Col>
        </Row>
        <div style="position: relative;">
            <Table :columns="roleColumns" :data="roleData" @on-selection-change="setSelection">
            </Table>
            <Spin size="large" fix v-show="showSpin">
                {{spinMsg}}
            </Spin>
        </div>
        <Page :total="totalElements" :page-size="searchData.size" @on-change="changePage" show-sizer
              :page-size-opts="[5, 10, 20, 30, 40]"
              show-total @on-page-size-change="changePageSize" style="margin-top:30px;text-align:center;"></Page>
    </div>
</template>
<script>
    export default {
        name: 'roleList',
        data () {
            return {
                showSpin: false,
                spinMsg: '加载中,请稍候...',
                //
                iosCreateId: '',
                iosTrashId: '',
                iosHandId: '',
                //
                // 按钮是否显示加载中
                roleColumns: [
                    {
                        type: 'selection',
                        minWidth: 60,
                        fixed: 'left',
                        align: 'center'
                    },
                    {
                        title: '操作',
                        minWidth: 200,
                        key: 'action',
                        fixed: 'right',
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('span', [
                                    h('tooltip', {
                                        props: {
                                            content: '编辑',
                                            trigger: 'hover',
                                            size: 'small',
                                            placement: 'bottom'
                                        },
                                        style: {
                                            marginRight: '3px'

                                        }
                                    }, [
                                        h('Icon', {
                                            props: {
                                                type: 'ios-create-outline',
                                                size: 18
                                            },
                                            on: {
                                                click: () => {
                                                    this.showSaveRoleModal(params.row);
                                                }
                                            }

                                        })
                                    ])
                                ]),
                                h('span', [
                                    h('tooltip', {
                                        props: {
                                            content: '删除',
                                            trigger: 'hover',
                                            size: 'small',
                                            placement: 'bottom'
                                        },
                                        style: {
                                            marginRight: '3px'

                                        }
                                    }, [
                                        h('Icon', {
                                            props: {
                                                type: 'ios-trash-outline',
                                                size: 18
                                            },
                                            on: {
                                                click: () => {
                                                    let ids = [params.row.id];
                                                    this.delRole(ids);
                                                }
                                            }

                                        })
                                    ])
                                ]),
                                h('span', [
                                    h('tooltip', {
                                        props: {
                                            content: '权限设置',
                                            trigger: 'hover',
                                            size: 'small',
                                            placement: 'bottom'
                                        },
                                        style: {
                                            marginRight: '3px'

                                        }
                                    }, [
                                        h('Icon', {
                                            props: {
                                                type: 'ios-hand-outline',
                                                size: 18
                                            },
                                            on: {
                                                click: () => {
                                                    this.showMenuPermission(params.row);
                                                }
                                            }

                                        })
                                    ])
                                ])
                            ]);
                        }
                    },
                    {
                        title: '名称',
                        minWidth: 200,
                        fixed: 'left',
                        align: 'center',
                        key: 'name'
                    },
                    {
                        title: '描述',
                        key: 'detail',
                        minWidth: 200,
                        maxWidth: 1177,
                        align: 'center'
                    },
                    {
                        title: '创建时间',
                        key: 'createTime',
                        minWidth: 200,
                        align: 'center'
                    }
                ],
                size: 10,
                totalElements: 1,
                // 角色列表数据
                roleData: [],
                // 选中ID
                selectionIds: [],
                // 查询框数据
                searchData: {
                    isSearching: false,
                    page: 0,
                    size: 10,
                    name: null
                },
                // 保存角色弹出框
                saveRoleModal: {
                    // 是否打开弹出框
                    saveRoleWin: false,
                    // 弹出框title
                    modalName: '',
                    // 角色信息
                    saveRole: {},
                    positionValidation: {
                        name: '',
                        detail: ''
                    },
                    // 校验
                    ruleValidation: {
                        // 职位名称
                        name: [
                            {required: true, message: '请输入角色名称', trigger: 'blur'},
                            {type: 'string', max: 20, message: '角色名称不能超过20个字', trigger: 'blur'},
                            {
                                type: 'string',
                                pattern: /^[a-zA-Z0-9\u4e00-\u9fa5_]*$/,
                                message: '角色名称只能输入汉字数字英文下划线',
                                trigger: 'blur'
                            }
                        ],
                        detail: [
                            {type: 'string', max: 150, message: '描述不能超过100个字', trigger: 'blur'},
                            {
                                type: 'string',
                                pattern: /^[a-zA-Z0-9\u4e00-\u9fa5_]*$/,
                                message: '描述只能输入汉字数字英文下划线',
                                trigger: 'blur'
                            }
                        ]
                    },
                    loading: true
                },
                bindMenuModal: {
                    loading: true,
                    bindMenuWin: false,
                    roleId: null,
                    tree: [],
                    //首页模块
                    moduleTreeHome: [],
                    //销售模块
                    moduleTreeStatistics: [],
                    bindMenu: []
                }
            };
        },
        methods: {
            // 删除角色
            delRole (roleIds) {
                let confirmMsg = null;
                if (!roleIds || roleIds.length < 1) {
                    this.$Message.error('请先选择要删除的角色');
                    return;
                }
                if (roleIds.length == 1) {
                    confirmMsg = '是否删除该角色？';
                } else {
                    confirmMsg = '是否删除所选角色？';
                }
                let v = this;
                this.$Modal.confirm({
                    title: 'Title',
                    content: confirmMsg,
                    onOk: () => {
                        this.showSpin = true;
                        this.spinMsg = '删除中，请稍后...';
                        depot.post({
                            url: this.URL.USER.UPDATE_ROLE_IS_DEL,
                            data: roleIds,
                            cb: (data) => {
                                this.showSpin = false;
                                if (data.code === 0) {
                                    this.$Message.success('删除成功');
                                    this.search();
                                } else {
                                    this.$Message.error(data.message);
                                }
                            },
                            ce: (error) => {
                                this.showSpin = false;
                            }
                        });
                    },
                    onCancel: () => {

                    }
                });
            },
            // 刷新
            refresh () {
                this.getRoleList(this.searchData);
            },
            // 查询角色列表
            getRoleList (params) {
                this.showSpin = true;
                let queryParams = null;
                if (params.isSearching) {
                    queryParams = params;
                }
                // 获取角色列表
                depot.get({
                    url: this.URL.USER.FIND_ROLE_PAGE,
                    config: {
                        params: queryParams
                    },
                    cb: (data) => {
                        this.showSpin = false;
                        if (data.code === 0) {
                            this.roleData.splice(0, this.roleData.length);
                            this.roleData = data.data.content;
                            this.size = data.data.size;
                            this.totalElements = data.data.totalElements;
                        } else if (data.code === 999) {
                            this.$Message.error(data.message);
                        }
                    },
                    ce: (error) => {
                        this.showSpin = false;
                    }
                });
            },
            // 重置查询框
            resetSearchData () {
                this.searchData = {
                    isSearching: false,
                    page: 0,
                    size: 10,
                    name: null
                };
                this.getRoleList(this.searchData);
            },
            // 查询
            search () {
                this.searchData.isSearching = true;
                this.getRoleList(this.searchData);
            },
            saveRoleInfo (name) {
                var vue = this;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        depot.post({
                            url: vue.URL.USER.SAVE_ROLE,
                            data: vue.saveRoleModal.saveRole,
                            cb: (data) => {
                                if (data.code === 0) {
                                    vue.$Message.success('提交成功');
                                    vue.saveRoleModal.saveRoleWin = false;
                                    vue.search();
                                } else {
                                    vue.saveRoleModal.loading = false;
                                    this.$nextTick(() => {
                                        vue.saveRoleModal.loading = true;
                                    });
                                    vue.$Message.error(data.message);
                                }
                            },
                            ce: (error) => {
                                vue.$Message.error(data.message);
                            }
                        });
                    } else {
                        vue.saveRoleModal.loading = false;
                        this.$nextTick(() => {
                            vue.saveRoleModal.loading = true;
                        });
                        vue.$Message.error('您输入的信息有误，请检查');
                    }
                });
            },
            showSaveRoleModal (role) {
                if (role) {
                    this.saveRoleModal.modalName = '编辑角色';
                    this.saveRoleModal.saveRole.id = role.id;
                    this.saveRoleModal.saveRole.name = role.name;
                    this.saveRoleModal.saveRole.detail = role.detail;
                } else {
                    this.saveRoleModal.modalName = '新增角色';
                    this.saveRoleModal.saveRole.id = null;
                    this.saveRoleModal.saveRole.name = null;
                    this.saveRoleModal.saveRole.detail = null;
                }
                this.saveRoleModal.saveRoleWin = true;
            },
            // 设置选中项
            setSelection (selection) {
                this.selectionIds = [];
                if (selection && selection.length > 0) {
                    selection.forEach((selectedData) => {
                        if (selectedData && !!selectedData.id) {
                            this.selectionIds.push(selectedData.id);
                        }
                    });
                }
            },
            // 翻页
            changePage (val) {
                this.searchData.page = val - 1;
                this.search();
            },
            // 修改页面数据量
            changePageSize (val) {
                this.searchData.size = val;
                this.search();
            },
            // 显示绑定菜单modal
            showMenuPermission (role) {
                console.log(role, 'rolerole');
                if (!role) {
                    this.$Message.error('获取角色信息失败');
                    return;
                }
                // 如果不存在则去获取全部菜单
                this.bindMenuModal.roleId = role.id;
                this.bindMenuModal.bindMenu = role.resourceList;
                this.getAllMenu();
                this.getAllModule();
                this.bindMenuModal.bindMenuWin = true;
            },
            // 绑定菜单
            bindMenu () {
                var checkedNodes = this.$refs['menuTree'].getCheckedNodes();
                var checkedModuleNodesHome = this.$refs['menuModuleTreeHome'].getCheckedNodes();
                var checkedModuleNodesStatistics = this.$refs['menuModuleTreeStatistics'].getCheckedNodes();
                var vue = this;
                if (!checkedNodes || checkedNodes.length == 0) {
                    this.$Message.error('请勾选菜单');
                    vue.bindMenuModal.loading = false;
                    this.$nextTick(() => {
                        vue.bindMenuModal.loading = true;
                    });
                    return;
                }
                if (!checkedModuleNodesHome || checkedModuleNodesHome.length == 0) {
                    this.$Message.error('请勾选首页展示模块信息');
                    vue.bindMenuModal.loading = false;
                    this.$nextTick(() => {
                        vue.bindMenuModal.loading = true;
                    });
                    return;
                }
                let resourceIds = [];
                checkedNodes.forEach((node) => {
                    if (node) {
                        resourceIds.push(node.id);
                    }
                });
                checkedModuleNodesHome.forEach((node) => {
                    if (node) {
                        resourceIds.push(node.id);
                    }
                });
                checkedModuleNodesStatistics.forEach((node) => {
                    if (node) {
                        resourceIds.push(node.id);
                    }
                });
                depot.post({
                    url: vue.URL.USER.BIND_ROLE_AND_RESOURCE + '?id=' +
                    this.bindMenuModal.roleId + '&type=MENU',
                    data: resourceIds,
                    cb: (data) => {
                        if (data.code === 0) {
                            vue.$Message.success('提交成功');
                            this.bindMenuModal.bindMenuWin = false;
                            this.bindMenuModal.roleId = null;
                            this.bindMenuModal.tree = [];
                            this.bindMenuModal.bindMenu = [];
                            this.search();
                        } else {
                            vue.bindMenuModal.loading = false;
                            this.$nextTick(() => {
                                vue.bindMenuModal.loading = true;
                            });
                            vue.$Message.error(data.message);
                        }
                    },
                    ce: (error) => {
                        vue.$Message.error(data.message);
                    }
                });
            },
            // 获取全部菜单
            getAllMenu () {
                depot.get({
                    url: this.URL.USER.FIND_ALL_MENUS,
                    data: this.saveRoleModal.saveRole,
                    cb: (data) => {
                        if (data.code === 0) {
                            this.mergeTreeData(data.data);
                            this.bindMenuModal.tree = data.data;
                        } else {
                            this.$Message.error(data.message);
                        }
                    },
                    ce: (error) => {
                        this.$Message.error(data.message);
                    }
                });
            },
            // 获取全部模块
            getAllModule () {
                depot.get({
                    url: this.URL.USER.FIND_ALL_MODULE,
                    cb: (data) => {
                        if (data.code === 0) {
                            let moduleList = data.data
                            this.mergeTreeData(moduleList);
                            this.bindMenuModal.moduleTreeHome = [];
                            this.bindMenuModal.moduleTreeStatistics = [];
                            moduleList.forEach((item) => {
                                if(item){
                                    if(item.type == 'MODULE_HOME'){
                                        this.bindMenuModal.moduleTreeHome.push(item);
                                    }else if(item.type == 'MODULE_STATISTICS'){
                                        this.bindMenuModal.moduleTreeStatistics.push(item);
                                    }
                                }
                            });
                        } else {
                            this.$Message.error(data.message);
                        }
                    },
                    ce: (error) => {
                        this.$Message.error(data.message);
                    }
                });
            },
            mergeTreeData (menuList) {
                if (menuList && menuList.length > 0) {
                    menuList.forEach((menu) => {
                        if (menu) {
                            menu.title = menu.name;
                            if (menu.remark) {
                                menu.title = menu.title + '(' + menu.remark + ')';
                            }
                            menu.expand = false;
                            try {
                                this.bindMenuModal.bindMenu.forEach((resource) => {
                                    // 不回显父级·只做子集的回显
                                    if (!menu.children || menu.children.length == 0) {
                                        if (menu.id == resource.id) {
                                            menu.checked = true;
                                            throw new Error('跳出循环');
                                        }
                                    }
                                });
                            } catch (e) {
                                menu.expand = true;
                            }
                            this.mergeTreeData(menu.children);
                        }
                    });
                }
            },
            // 关闭窗口时清空属性数据
            resetMenu () {
                // 关闭时
                if (!this.bindMenuModal.bindMenuWin) {
                    this.bindMenuModal.roleId = null;
                    this.bindMenuModal.tree = [];
                    this.bindMenuModal.moduleTreeHome = [];
                    this.bindMenuModal.moduleTreeStatistics = [];
                    this.bindMenuModal.bindMenu = [];
                }
            }
        },
        mounted () {
            // 查询数据
            this.refresh();
        }
    };
</script>
